import {
  reqAddAddress, reqAddressList, reqAddressInfo,
  reqUpdateAddress
} from '../../../../../pages/api/address'
import QQMapWx from '../../../../../pages/libs/qqmap-wx-jssdk'
import Schema from 'async-validator'
import { toast } from '../../../../../utils/extendAPI'
Page({
  // 页面的初始数据
  data: {
    name: '',
    phone: '',
    provinceName: '',
    provinceCode: '',
    cityName: '',
    cityCode: '',
    districtName: '',
    districtCode: '',
    address: '',
    fullAddress: '',
    isDefault: false

  },

  // 保存收货地址
  async saveAddrssForm() {
    const { provinceName, cityName, districtName, address, isDefault } = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: isDefault ? 1 : 0
    }
    const res = this.updataAddress ? await reqUpdateAddress(params) : await reqAddAddress(params)
    if (res.code === 200) {
      wx.navigateBack({
        success: () => {
          wx.showToast({
            title: this.updataAddress ? '修改收货地址成功！' : '新增收货地址成功！',
            icon: 'none',
            duration: '2000',
            mask: true,
          })
        }
      })

    }
  },
  validatorAddress(params) {
    const nameRegExp = '^[a-xA\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    //创建验证规则
    const rules = {
      name: [{ required: true, message: '请输入收货人姓名' }, { pattern: nameRegExp, message: '收货人姓名不合法' }],
      phone: [{ required: true, message: '请输入收货人手机号' }, { pattern: phoneReg, message: '收货人手机号不合法' }],
      provinceName: { required: true, message: '请选择收货人所在地区' },
      address: { required: true, message: '请输入详细地址' },
    }
    //传入验证规则进行实例化
    const validator = new Schema(rules)
    //将校验的结果通过promise的形式返回给调用者
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.showToast({
            title: errors[0].message,
            icon: 'none',
            duration: '2000',
            mask: true,
          })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  // 省市区选择
  onAddressChange(event) {
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode, cityCode, districtCode] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  async onLoacation() {
    //维度，经度，搜索的地点
    const { latitude, longitude, name } = await wx.chooseLocation()
    this.qqmapwx.reverseGeocoder({
      location: {
        latitude,
        longitude
      },

      success: (res) => {
        //获取省市区，省市区编码
        const { adcode, province, city, district } = res.result.ad_info
        //获取街道，门牌（街道，门牌，可能为空）
        const { street, street_number } = res.result.address_component
        //获取标准地址
        const { standard_address } = res.result.formatted_addresses
        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), '00'),
          districtName: district,
          districtCode: adcode && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name
        })
      }
    })
  },
  async showAddressInfo(id) {
    if (!id) return

    this.updataAddress = id
    wx.setNavigationBarTitle({
      title: this.updataAddress ? '修改收货地址' : '新增收货地址'
    })
    const { data } = await reqAddressInfo(id)
    this.setData({
      ...data
    })
  },

  onLoad(options) {
    console.log(this);
    this.showAddressInfo(options.id)

    this.qqmapwx = new QQMapWx({
      key: 'YRQBZ-ABT33-FKH3Y-RJJHB-DN5J6-DABUL'
    })
  }

})
